package view.swing;

import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;

import view.INewPlayerView;

/**
 * cette classe est un panel affichant autant de textfield que le nombre de
 * joueurs sélectionnés
 * 
 * @author Lucile Gramusset et Guillaume Poussel
 * 
 */
public class NewPlayerView extends JPanel implements INewPlayerView {

    private static final long serialVersionUID = 1L;
    private ArrayList<JTextField> players;
    private int nbPlayer = 2;

    public NewPlayerView() {
        this.players = new ArrayList<JTextField>();
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        for (int i = 0; i < 4; i++) {
            JTextField jtf = new JTextField();
            jtf.setAlignmentX(CENTER_ALIGNMENT);
            jtf.setAlignmentY(CENTER_ALIGNMENT);
            players.add(jtf);
            add(jtf);
        }
        buildNewPlayerPanel();
    }

    public ArrayList<String> getField() {
        ArrayList<String> name = new ArrayList<String>();
        for (int i = 0; i < this.players.size(); i++) {
            if (!this.players.get(i).getText().equals(""))
                name.add(this.players.get(i).getText());
        }

        return name;
    }

    private void buildNewPlayerPanel() {
        
        for (int i = 0; i < nbPlayer; i++) {
            players.get(i).setEnabled(true);
        }
        for (int i = nbPlayer; i < players.size(); i++) {
            players.get(i).setText("");
            players.get(i).setEnabled(false);
        }
        validate();

    }

    public void updateUI(int nbplayer) {
        this.nbPlayer = nbplayer;
        buildNewPlayerPanel();
        this.updateUI();
    }

    @Override
    public synchronized void addKeyListener(KeyListener l) {
        for (JTextField jtf : players) {
            jtf.addKeyListener(l);
        }
        super.addKeyListener(l);
    }

    @Override
    public int getNumberPlayers() {
        return nbPlayer;
    }

}
